﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Processing;
using Traceable.App.DTOS;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Processing
{
    public class GetProcessingHandler : IRequestHandler<GetProcessingCommand, ApiResult<ProcessingDto>>
    {
        private readonly IBaseRepository<Processing_Table> _processingRepo;
        private readonly IBaseRepository<Traceable_Table> _traceableRepositry;
        private readonly IMapper _mapper;

        public GetProcessingHandler(IBaseRepository<Processing_Table> processingRepo, IMapper mapper, IBaseRepository<Traceable_Table> traceableRepositry)
        {
            _processingRepo = processingRepo;
            _mapper = mapper;
            _traceableRepositry = traceableRepositry;
        }
        /// <summary>
        /// 获取加工基本信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<ProcessingDto>> Handle(GetProcessingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ProcessingDto> result = new ApiResult<ProcessingDto>();

            var processing = _processingRepo.GetAll().Where(p => p.Batch_Id == request.Batch_Id && !p.IsDelete).FirstOrDefault();
            if(processing != null)
            {
                result.Code = StatusEnum.OK;
                result.Data = _mapper.Map<ProcessingDto>(processing);
                result.Message = "获取成功";
                var goods = _traceableRepositry.GetAll().Where(p => p.Batch == request.Batch_Id).FirstOrDefault();
                if (goods.Perfect <= 70)
                {
                    goods.Perfect += 30;
                }
                var res = _traceableRepositry.Update(goods);
            }
           
            return Task.FromResult(result);
        }
    }
}
